﻿using System;
using System.Threading;

namespace Framework.Common.Ioc
{
    public class TryInterceptor : IInterceptor
    {
        private int tryTimes = 2;
        /// <summary>
        /// 重试次数
        /// </summary>
        public int TryTimes
        {
            get { return tryTimes; }
            set { tryTimes = value; }
        }

        private int milliSeconds = 10;
        /// <summary>
        /// 等待**时间后重试
        /// </summary>
        public int MilliSeconds
        {
            get { return milliSeconds; }
            set { milliSeconds = value; }
        }

        public void Intercept(IInvocation invocation)
        {
            Exception exceptionDetail = null;
            while (TryTimes > 0)
            {
                try
                {
                    invocation.Proceed();
                    return;
                }
                catch (Exception ex)
                {
                    exceptionDetail = ex;
                    if (MilliSeconds > 0) Thread.Sleep(MilliSeconds);
                    TryTimes--;
                }
            }
            string key = Formatter.Format(invocation.InvocationTarget, invocation.Args, invocation.GetConcreteMethod());
            LogHelper.Fatal(key, exceptionDetail);
        }
    }
}
